package com.youkeyi.ddy.cloud.basic.hr.employee.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youkeyi.ddy.cloud.basic.hr.employee.entity.TblEmployee;
import com.youkeyi.ddy.cloud.basic.hr.employee.mapper.TblEmployeeDao;
import com.youkeyi.ddy.cloud.basic.hr.employee.param.QueryForBirthday;
import com.youkeyi.ddy.cloud.basic.hr.employee.service.TblEmployeeService;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.HrEmployeeCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.dto.HrEmployeeListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.dto.HrEmployeeListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.param.HrEmployeeCreateCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.param.HrEmployeeDeleteCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.param.HrEmployeeQueryCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.param.HrEmployeeUpdateCloudParam;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyCloudBasicHrConstant;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyCloudBasicPublicConstant;
import com.youkeyi.ddy.cloud.common.enums.ResponseCodeEnum;
import com.youkeyi.ddy.cloud.common.response.ResponseContent;
import com.youkeyi.ddy.cloud.common.utils.AESUtils;
import com.youkeyi.ddy.cloud.common.utils.SimpleUUidUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author xiawang.liu
 * @since 2024-04-28
 */
@Service
public class TblEmployeeController implements HrEmployeeCloudService {

    @Autowired
    private TblEmployeeService tblEmployeeService;
    @Resource
    private TblEmployeeDao tblEmployeeDao;

    @Override
    public HrEmployeeListCloudDto query(HrEmployeeQueryCloudParam param) {
        HrEmployeeListCloudDto dto = new HrEmployeeListCloudDto();
        if (null == param) {
            dto.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return dto;
        }

        if (CollectionUtils.isNotEmpty(param.getEmployeePrimaryKeys())) {
            param.getEmployeePrimaryKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getCorpKeys())) {
            param.getCorpKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getEmployeeCodes())) {
            param.getEmployeeCodes().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getAccounts())) {
            param.getAccounts().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getEmployeeStatuses())) {
            param.getEmployeeStatuses().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getDepartmentKeys())) {
            param.getDepartmentKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getPositionKeys())) {
            param.getPositionKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getPhones())) {
            param.getPhones().removeAll(Collections.singleton(null));
        }

        if (CollectionUtils.isNotEmpty(param.getConstellations())) {
            param.getConstellations().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getZodiacs())) {
            param.getZodiacs().removeAll(Collections.singleton(null));
        }

        QueryWrapper<TblEmployee> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .in(CollectionUtils.isNotEmpty(param.getEmployeePrimaryKeys()), TblEmployee::getPrimaryKey, param.getEmployeePrimaryKeys())
                .in(CollectionUtils.isNotEmpty(param.getCorpKeys()), TblEmployee::getCorpKey, param.getCorpKeys())
                .in(CollectionUtils.isNotEmpty(param.getEmployeeCodes()), TblEmployee::getEmployeeCode, param.getEmployeeCodes())
                .in(CollectionUtils.isNotEmpty(param.getAccounts()), TblEmployee::getAccount, param.getAccounts())
                .in(CollectionUtils.isNotEmpty(param.getEmployeeStatuses()), TblEmployee::getEmployeeStatus, param.getEmployeeStatuses())
                .in(CollectionUtils.isNotEmpty(param.getPhones()), TblEmployee::getPhone, param.getPhones())
                .in(CollectionUtils.isNotEmpty(param.getDepartmentKeys()), TblEmployee::getDepartmentKey, param.getDepartmentKeys())
                .in(CollectionUtils.isNotEmpty(param.getPositionKeys()), TblEmployee::getPositionKey, param.getPositionKeys())
                .in(CollectionUtils.isNotEmpty(param.getConstellations()), TblEmployee::getConstellation, param.getConstellations())
                .in(CollectionUtils.isNotEmpty(param.getZodiacs()), TblEmployee::getZodiac, param.getZodiacs())
                .like(StringUtils.isNotBlank(param.getNameFuzzy()), TblEmployee::getName, param.getNameFuzzy())
                .like(StringUtils.isNotBlank(param.getPhoneFuzzy()), TblEmployee::getPhone, param.getPhoneFuzzy())
                .like(StringUtils.isNotBlank(param.getEmailFuzzy()), TblEmployee::getEmail, param.getEmailFuzzy())
                .between(null != param.getEntryDateBegin() && null != param.getEntryDateEnd(), TblEmployee::getEntryDate, param.getEntryDateBegin(), param.getEntryDateEnd())
                .between(null != param.getRegularizationDateBegin() && null != param.getRegularizationDateEnd(), TblEmployee::getRegularizationDate, param.getRegularizationDateBegin(), param.getRegularizationDateEnd())
                .ne(TblEmployee::getIsDeleted, YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_YES.value())
        ;

        Page<TblEmployee> page = new Page<>();
        if (null != param.getCurrentPage() && null != param.getPageSize()) {
            page.setCurrent(param.getCurrentPage());
            page.setSize(param.getPageSize());
        } else {
            page.setCurrent(1);
            page.setSize(99999999);
        }
        Page<TblEmployee> employeeList = tblEmployeeService.page(page, wrapper);
        if (CollectionUtils.isNotEmpty(employeeList.getRecords())) {
            dto.setTotal(employeeList.getTotal());

            dto.setRows(setting(employeeList.getRecords()));
        }
        dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return dto;
    }

    @Override
    public HrEmployeeListCloudDto queryForBirthday(HrEmployeeQueryCloudParam param) {
        HrEmployeeListCloudDto dto = new HrEmployeeListCloudDto();
        if (null == param || null == param.getBirthdayBegin() || null == param.getBirthdayEnd()) {
            dto.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return dto;
        }

        if (CollectionUtils.isNotEmpty(param.getCorpKeys())) {
            param.getCorpKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getEmployeeCodes())) {
            param.getEmployeeCodes().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getEmployeeStatuses())) {
            param.getEmployeeStatuses().removeAll(Collections.singleton(null));
        }

        QueryForBirthday wrapper = new QueryForBirthday();
        wrapper.setBirthdayBegin(param.getBirthdayBegin());
        wrapper.setBirthdayEnd(param.getBirthdayEnd());
        wrapper.setEmployeeCodes(param.getEmployeeCodes());
        wrapper.setCorpKeys(param.getCorpKeys());
        wrapper.setEmployeeStatuses(param.getEmployeeStatuses());
        wrapper.setNameFuzzy(param.getNameFuzzy());

        Page<TblEmployee> page = new Page<>();
        if (null != param.getCurrentPage() && null != param.getPageSize()) {
            page.setCurrent(param.getCurrentPage());
            page.setSize(param.getPageSize());
        } else {
            page.setCurrent(1);
            page.setSize(99999999);
        }
        Page<TblEmployee> employeeList = tblEmployeeDao.queryForBirthday(page, wrapper);
        if (CollectionUtils.isNotEmpty(employeeList.getRecords())) {
            dto.setTotal(employeeList.getTotal());

            dto.setRows(setting(employeeList.getRecords()));
        }
        dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return dto;
    }

    /**
     * 设置返回值
     *
     * @param employeeList
     * @return
     */
    private List<HrEmployeeListItemCloudDto> setting(List<TblEmployee> employeeList) {
        List<HrEmployeeListItemCloudDto> items = new ArrayList<>();
        employeeList.forEach(employee -> {
            HrEmployeeListItemCloudDto item = new HrEmployeeListItemCloudDto();
            item.setEmployeePrimaryKey(employee.getPrimaryKey());
            item.setPrimaryKey(employee.getPrimaryKey());
            item.setEmployeeCode(employee.getEmployeeCode());
            item.setName(employee.getName());
            item.setFormerName(employee.getFormerName());
            if (StringUtils.isNotBlank(employee.getIdCard())) {
                String idCard;
                try {
                    idCard = AESUtils.decrypt(employee.getIdCard());
                } catch (Exception e) {
                    e.printStackTrace();
                    idCard = employee.getIdCard();
                }
                item.setIdCard(idCard);
            }
            item.setSex(employee.getSex());
            item.setBirthday(employee.getBirthday() != null ? employee.getBirthday().getTime() : null);
            item.setZodiac(employee.getZodiac());
            item.setConstellation(employee.getConstellation());
            item.setNationality(employee.getNationality());
            item.setNativePlace(employee.getNativePlace());
            item.setNickName(employee.getNickName());
            item.setProvince(employee.getProvince());
            item.setCity(employee.getCity());
            item.setArea(employee.getArea());
            item.setCurrentResidence(employee.getCurrentResidence());
            item.setMaritalStatus(employee.getMaritalStatus());
            item.setPhone(employee.getPhone());
            item.setEmail(employee.getEmail());
            item.setProfilePictureKey(employee.getProfilePictureKey());
            item.setPoliticalStatus(employee.getPoliticalStatus());
            item.setJoinLeagueDate(employee.getJoinLeagueDate() != null ? employee.getJoinLeagueDate().getTime() : null);
            item.setJoinPartyDate(employee.getJoinPartyDate() != null ? employee.getJoinPartyDate().getTime() : null);
            item.setHighestEducation(employee.getHighestEducation());
            item.setHighestDegree(employee.getHighestDegree());
            item.setStartWorkDate(employee.getStartWorkDate() != null ? employee.getStartWorkDate().getTime() : null);
            item.setEmergencyContact(employee.getEmergencyContact());
            item.setEmergencyContactPhone(employee.getEmergencyContactPhone());
            item.setOtherContact(employee.getOtherContact());
            item.setAccount(employee.getAccount());
            item.setDepartmentKey(employee.getDepartmentKey());
            item.setPositionKey(employee.getPositionKey());
            item.setOfficeLocation(employee.getOfficeLocation());
            item.setOfficePhone(employee.getOfficePhone());
            item.setEmployeeStatus(employee.getEmployeeStatus());
            item.setEmployeeStatusName(YoukeyiDdyCloudBasicHrConstant.HR_EMPLOYEE_STATUS.getName(item.getEmployeeStatus()));
            item.setJobNature(employee.getJobNature());
            item.setEntryDate(employee.getEntryDate() != null ? employee.getEntryDate().getTime() : null);
            item.setPlanEntryDate(employee.getPlanEntryDate() != null ? employee.getPlanEntryDate().getTime() : null);
            item.setEntryChannel(employee.getEntryChannel());
            item.setEntryChannelRecommendedBy(employee.getEntryChannelRecommendedBy());
            item.setProbationPeriod(employee.getProbationPeriod());
            item.setRegularizationDate(employee.getRegularizationDate() != null ? employee.getRegularizationDate().getTime() : null);
            item.setAttachmentKey(employee.getAttachmentKey());
            item.setResignationApplicationDate(employee.getResignationApplicationDate() != null ? employee.getResignationApplicationDate().getTime() : null);
            item.setResignationActualDate(employee.getResignationActualDate() != null ? employee.getResignationActualDate().getTime() : null);
            item.setResignationSettlementDate(employee.getResignationSettlementDate() != null ? employee.getResignationSettlementDate().getTime(): null);
            item.setResignationReason(employee.getResignationReason());
            item.setResignationDestination(employee.getResignationDestination());
            item.setResignationRemark(employee.getResignationRemark());
            item.setRemark(employee.getRemark());
            item.setIsDeleted(employee.getIsDeleted());
            item.setIsDeletedName(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO.getName(item.getIsDeleted()));
            item.setCreateTime(employee.getCreateTime() != null ? employee.getCreateTime().getTime() : null);
            item.setCreateUserKey(employee.getCreateUserKey());
            item.setCreateUserName(employee.getCreateUserName());
            item.setUpdateTime(employee.getUpdateTime() != null ? employee.getUpdateTime().getTime() : null);
            item.setUpdateUserKey(employee.getUpdateUserKey());
            item.setUpdateUserName(employee.getUpdateUserName());
            items.add(item);
        });
        return items;
    }

    @Override
    public ResponseContent create(HrEmployeeCreateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || StringUtils.isBlank(param.getName())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }
        TblEmployee employee = new TblEmployee();
        employee.setPrimaryKey(StringUtils.defaultIfEmpty(param.getEmployeePrimaryKey(), SimpleUUidUtils.getUuid()));
        employee.setCorpKey(param.getCorpKey());
        employee.setEmployeeCode(StringUtils.defaultIfEmpty(param.getEmployeeCode(), SimpleUUidUtils.getInvidID(5) + ""));
        employee.setName(param.getName());
        employee.setFormerName(param.getFormerName());
        employee.setIdCard(AESUtils.encrypt(param.getIdCard()));
        employee.setSex(param.getSex());
        employee.setBirthday(param.getBirthday() != null ? new Date(param.getBirthday()) : null);
        employee.setZodiac(param.getZodiac());
        employee.setConstellation(param.getConstellation());
        employee.setNationality(param.getNationality());
        employee.setNativePlace(param.getNativePlace());
        employee.setNickName(param.getNickName());
        employee.setProvince(param.getProvince());
        employee.setCity(param.getCity());
        employee.setArea(param.getArea());
        employee.setCurrentResidence(param.getCurrentResidence());
        employee.setMaritalStatus(param.getMaritalStatus());
        employee.setPhone(param.getPhone());
        employee.setEmail(param.getEmail());
        employee.setProfilePictureKey(param.getProfilePictureKey());
        employee.setPoliticalStatus(param.getPoliticalStatus());
        employee.setJoinLeagueDate(param.getJoinLeagueDate() != null ? new Date(param.getJoinLeagueDate()) : null);
        employee.setJoinPartyDate(param.getJoinPartyDate() != null ? new Date(param.getJoinPartyDate()) : null);
        employee.setHighestEducation(param.getHighestEducation());
        employee.setHighestDegree(param.getHighestDegree());
        employee.setStartWorkDate(param.getStartWorkDate() != null ? new Date(param.getStartWorkDate()) : null);
        employee.setEmergencyContact(param.getEmergencyContact());
        employee.setEmergencyContactPhone(param.getEmergencyContactPhone());
        employee.setOtherContact(param.getOtherContact());
        employee.setAccount(param.getAccount());
        employee.setDepartmentKey(param.getDepartmentKey());
        employee.setPositionKey(param.getPositionKey());
        employee.setOfficeLocation(param.getOfficeLocation());
        employee.setOfficePhone(param.getOfficePhone());
        employee.setEmployeeStatus(param.getEmployeeStatus());
        employee.setJobNature(param.getJobNature());
        employee.setEntryDate(param.getEntryDate() != null ? new Date(param.getEntryDate()) : null);
        employee.setPlanEntryDate(param.getPlanEntryDate() != null ? new Date(param.getPlanEntryDate()) : null);
        employee.setEntryChannel(param.getEntryChannel());
        employee.setEntryChannelRecommendedBy(param.getEntryChannelRecommendedBy());
        employee.setProbationPeriod(param.getProbationPeriod());
        employee.setRegularizationDate(param.getRegularizationDate() != null ? new Date(param.getRegularizationDate()) : null);
        employee.setAttachmentKey(param.getAttachmentKey());
        employee.setResignationApplicationDate(param.getResignationApplicationDate() != null ? new Date(param.getResignationApplicationDate()) : null);
        employee.setResignationActualDate(param.getResignationActualDate() != null ? new Date(param.getResignationActualDate()) : null);
        employee.setResignationSettlementDate(param.getResignationSettlementDate() != null ? new Date(param.getResignationSettlementDate()) : null);
        employee.setResignationReason(param.getResignationReason());
        employee.setResignationDestination(param.getResignationDestination());
        employee.setResignationRemark(param.getResignationRemark());
        employee.setRemark(param.getRemark());
        employee.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_NO.value());
        employee.setCreateUserKey(param.getCreateUserKey());
        employee.setCreateUserName(param.getCreateUserName());
        employee.setCreateTime(new Date());
        boolean save = tblEmployeeService.save(employee);
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
            return rc;
        }
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        rc.setKey(employee.getPrimaryKey());
        return rc;
    }

    @Override
    public ResponseContent update(HrEmployeeUpdateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || StringUtils.isBlank(param.getEmployeePrimaryKey())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }

        UpdateWrapper<TblEmployee> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .eq(TblEmployee::getPrimaryKey, param.getEmployeePrimaryKey());
        TblEmployee employee = new TblEmployee();
        employee.setPrimaryKey(param.getEmployeePrimaryKey());
        employee.setEmployeeCode(param.getEmployeeCode());
        employee.setName(param.getName());
        employee.setFormerName(param.getFormerName());
        employee.setIdCard(AESUtils.encrypt(param.getIdCard()));
        employee.setSex(param.getSex());
        employee.setBirthday(param.getBirthday() != null ? new Date(param.getBirthday()) : null);
        employee.setZodiac(param.getZodiac());
        employee.setConstellation(param.getConstellation());
        employee.setNationality(param.getNationality());
        employee.setNativePlace(param.getNativePlace());
        employee.setNickName(param.getNickName());
        employee.setProvince(param.getProvince());
        employee.setCity(param.getCity());
        employee.setArea(param.getArea());
        employee.setCurrentResidence(param.getCurrentResidence());
        employee.setMaritalStatus(param.getMaritalStatus());
        employee.setPhone(param.getPhone());
        employee.setEmail(param.getEmail());
        employee.setProfilePictureKey(param.getProfilePictureKey());
        employee.setPoliticalStatus(param.getPoliticalStatus());
        employee.setJoinLeagueDate(param.getJoinLeagueDate() != null ? new Date(param.getJoinLeagueDate()) : null);
        employee.setJoinPartyDate(param.getJoinPartyDate() != null ? new Date(param.getJoinPartyDate()) : null);
        employee.setHighestEducation(param.getHighestEducation());
        employee.setHighestDegree(param.getHighestDegree());
        employee.setStartWorkDate(param.getStartWorkDate() != null ? new Date(param.getStartWorkDate()) : null);
        employee.setEmergencyContact(param.getEmergencyContact());
        employee.setEmergencyContactPhone(param.getEmergencyContactPhone());
        employee.setOtherContact(param.getOtherContact());
        employee.setAccount(param.getAccount());
        employee.setDepartmentKey(param.getDepartmentKey());
        employee.setPositionKey(param.getPositionKey());
        employee.setOfficeLocation(param.getOfficeLocation());
        employee.setOfficePhone(param.getOfficePhone());
        employee.setEmployeeStatus(param.getEmployeeStatus());
        employee.setJobNature(param.getJobNature());
        employee.setEntryDate(param.getEntryDate() != null ? new Date(param.getEntryDate()) : null);
        employee.setPlanEntryDate(param.getPlanEntryDate() != null ? new Date(param.getPlanEntryDate()) : null);
        employee.setEntryChannel(param.getEntryChannel());
        employee.setEntryChannelRecommendedBy(param.getEntryChannelRecommendedBy());
        employee.setProbationPeriod(param.getProbationPeriod());
        employee.setRegularizationDate(param.getRegularizationDate() != null ? new Date(param.getRegularizationDate()) : null);
        employee.setAttachmentKey(param.getAttachmentKey());
        employee.setResignationApplicationDate(param.getResignationApplicationDate() != null ? new Date(param.getResignationApplicationDate()) : null);
        employee.setResignationActualDate(param.getResignationActualDate() != null ? new Date(param.getResignationActualDate()) : null);
        employee.setResignationSettlementDate(param.getResignationSettlementDate() != null ? new Date(param.getResignationSettlementDate()) : null);
        employee.setResignationReason(param.getResignationReason());
        employee.setResignationDestination(param.getResignationDestination());
        employee.setResignationRemark(param.getResignationRemark());
        employee.setRemark(param.getRemark());
        employee.setUpdateUserKey(param.getUpdateUserKey());
        employee.setUpdateUserName(param.getUpdateUserName());
        employee.setUpdateTime(new Date());
        boolean save = tblEmployeeService.update(employee, wrapper);
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
            return rc;
        }
        return rc;
    }

    @Override
    public ResponseContent delete(HrEmployeeDeleteCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || CollectionUtils.isEmpty(param.getEmployeePrimaryKeys())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }
        UpdateWrapper<TblEmployee> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .in(TblEmployee::getPrimaryKey, param.getEmployeePrimaryKeys());

        TblEmployee employee = new TblEmployee();
        employee.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_YES.value());
        employee.setUpdateUserKey(param.getUpdateUserKey());
        employee.setUpdateUserName(param.getUpdateUserName());
        employee.setUpdateTime(new Date());
        boolean save = tblEmployeeService.update(employee, wrapper);
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
        }
        return rc;
    }
}
